package com.wentao.thisService.common;

import com.wentao.thisCommon.annotation.MethodAuthority;
import com.wentao.thisCommon.model.BaseContent;
import com.wentao.thisCommon.model.ResultBase;
import com.wentao.thisFacade.common.UserInfo;
import com.wentao.thisFacade.common.enums.ConstString;
import com.wentao.thisFacade.common.enums.ExceptionCode;
import com.wentao.thisService.common.redis.RedisExecutor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class AuthorityAop {

    @Autowired
    RedisExecutor redisExecutor;

    @Pointcut("@annotation(com.wentao.thisCommon.annotation.MethodAuthority)")
    public void checkAuthority() {
    }

//    private static final String[] ALLOW_HEADS = {"app-id", "serial-number", "request-time", "device-id", "app-version", "market", "sign", "customer-id", "access-token", "os-version", "phone-models", "app-stage", "X-Token", "content-type"};

    @Around("checkAuthority() && @annotation(methodAuthority)")
    public Object Interceptor(ProceedingJoinPoint pjp, MethodAuthority methodAuthority) throws Throwable {
        Object[] args = pjp.getArgs();
//        EnumsBase baseVal = null;
        Object rtn = null;

        try {
            if (methodAuthority.permissionCode().length == 0) {
                rtn = pjp.proceed();
            } else {
                for (Object arg : args) {
                    if (arg instanceof BaseContent) {
                        BaseContent head = (BaseContent) arg;
//                        String key = String.format("%s_%s", head.getToken(), head.getUserId());
//                        UserInfoEntity user = RedisExecutor.getMap(ConstString.Login, key, UserInfoEntity.class);
                        UserInfo user = RedisExecutor.getMap(ConstString.USER_INFO, head.getUserId(), UserInfo.class);
                        if (null != user) {
                            String code = user.getRoleCode();
                            // TODO: 2020/3/28 验证权限逻辑要重写
                            for (String methodCode : methodAuthority.permissionCode())
                                if (code.equals(methodCode)) {
                                    rtn = pjp.proceed();
                                }
                        } else {
                            rtn = pjp.proceed();
                        }
                    }
                }
            }
        } catch (Exception e) {
            rtn = new ResultBase<>(
                    null,
                    ExceptionCode.SYSTEM_ERROR.getMessage(),
                    ExceptionCode.SYSTEM_ERROR.getCode());

            System.out.print(e.getMessage());
            e.printStackTrace();
        }

        return rtn;
    }

}
